export function findDeep(list = [], predicate) {
  if (!list || !list.length) {
    return;
  }
  for (const item of list) {
    if (predicate(item)) return item;
    if (item.children && item.children.length) {
      const res = findDeep(item.children, predicate);
      if (res) return res;
    }
  }
}

export function getRootParent(list = [], predicate) {
  function match(data = {}, predicate) {
    if (predicate(data)) return true;
    if (data.children && data.children.length) {
      for (const item of data.children) {
        if (match(item, predicate)) return true;
      }
    }
  }
  if (!list || !list.length) {
    return;
  }
  for (const item of list) {
    if (match(item, predicate)) {
      return item;
    }
  }
}

export function getLeafList(data = {}) {
  function getLeafDeep(data) {
    if (!data || typeof data !== 'object') return [];
    if (!Array.isArray(data.children)) {
      return [data.value];
    }
    return data.children.reduce((res, item) => {
      return [].concat(res, getLeafDeep(item));
    }, []);
  }
  return getLeafDeep(data);
}

export function turnDataList2DataObj(arr = []) {
  if (!arr || !arr.length) return {};
  return arr.reduce((res, item) => {
    return Object.assign(res, {
      [item.value]: getLeafList(item),
    });
  }, {});
}

export function getDefaultSelectKeys(list = [], ignores) {
  if (!list || !list.length) return [];
  if (!Array.isArray(ignores)) {
    ignores = [];
  }

  const isValid = (obj) => obj && (obj.value === 0 || !!obj.value);
  const isIgnore = (obj) => ignores.includes(obj.value);
  const isChecked = (obj) => obj.checked !== false;

  return list.reduce((res, item) => {
    if (!isValid(item) || !isChecked(item) || isIgnore(item)) {
      return res;
    }
    const children = getDefaultSelectKeys(item.children);
    return [].concat(res, children.length ? children : [item.value]);
  }, []);
}
